package com.sakura.oj.sandbox.config;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.DisposableBean;

import java.io.IOException;
import java.net.URI;
import java.time.Duration;

/**
 * Docker配置类
 * 负责创建和管理DockerClient Bean
 */
@Slf4j
@Configuration
public class DockerConfig implements DisposableBean {

    private DockerClient dockerClient;

    /**
     * 创建DockerClient Bean
     * 
     * @return DockerClient实例
     */
    @Bean
    public DockerClient dockerClient() {
        log.info("初始化Docker客户端...");
        
        // 根据操作系统选择适合的连接方式
        String osName = System.getProperty("os.name").toLowerCase();
        URI dockerHost;
        
        if (osName.contains("windows")) {
            // Windows系统使用命名管道
            dockerHost = URI.create("npipe:////./pipe/docker_engine");
        } else {
            // Linux/Mac系统使用Unix socket
           dockerHost = URI.create("unix:///var/run/docker.sock");
        }
        
        // 配置HTTP客户端
        ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(dockerHost)
                .connectionTimeout(Duration.ofSeconds(30))
                .responseTimeout(Duration.ofSeconds(45))
                .build();
        
        // 创建Docker客户端
        this.dockerClient = DockerClientBuilder.getInstance()
                .withDockerHttpClient(httpClient)
                .build();
        
        log.info("Docker客户端初始化完成");
        return this.dockerClient;
    }

    /**
     * 当Spring容器关闭时，关闭Docker客户端连接
     */
    @Override
    public void destroy() throws Exception {
        if (this.dockerClient != null) {
            try {
                log.info("正在关闭Docker客户端连接...");
                this.dockerClient.close();
                log.info("Docker客户端连接已关闭");
            } catch (IOException e) {
                log.error("关闭Docker客户端连接时出错", e);
            }
        }
    }
} 